package com.agileai.portal.controller.auth;

import java.util.List;

import com.agileai.domain.DataParam;
import com.agileai.hotweb.annotation.PageAction;
import com.agileai.hotweb.controller.core.QueryModelListHandler;
import com.agileai.hotweb.domain.FormSelectFactory;
import com.agileai.hotweb.renders.ViewRenderer;
import com.agileai.portal.bizmoduler.SecurityAuthorizationConfig;
import com.agileai.portal.bizmoduler.auth.SecurityUserQuery;
import com.agileai.portal.filter.UserCacheManager;

public class SecurityUserQueryListHandler
        extends QueryModelListHandler {
    public SecurityUserQueryListHandler() {
        super();
        this.serviceId = buildServiceId(SecurityUserQuery.class);
    }

    protected void processPageAttributes(DataParam param) {
        initMappingItem("USER_STATE",
                        FormSelectFactory.create("SYS_VALID_TYPE").getContent());
    }
    @PageAction
    public ViewRenderer addUserTreeRelation(DataParam param){
    	String roleId = param.get("roleId");
    	String userIds = param.get("userIds");
    	getService().addUserTreeRelation(roleId, userIds.split(","));
    	
    	SecurityAuthorizationConfig authorizationConfig = (SecurityAuthorizationConfig)this.lookupService(SecurityAuthorizationConfig.class);
    	List<String> userCodeList = authorizationConfig.findUserCodeListByRoleId(roleId);
    	if (userCodeList != null && userCodeList.size() > 0){
    		for (int i=0;i < userCodeList.size();i++){
    			String userCode = userCodeList.get(i);
    			UserCacheManager.getOnly().removeUser(userCode);
    		}
    	}
    	return this.prepareDisplay(param);
    }
    @PageAction
    public ViewRenderer delUserTreeRelation(DataParam param){
    	String roleId = param.get("ROLE_ID");
    	String userId = param.get("USER_ID");
    	SecurityAuthorizationConfig authorizationConfig = (SecurityAuthorizationConfig)this.lookupService(SecurityAuthorizationConfig.class);
    	String userCode = authorizationConfig.findUserCodeByUserId(userId);
    	UserCacheManager.getOnly().removeUser(userCode);
    	getService().delUserTreeRelation(roleId, userId);
    	return this.prepareDisplay(param);
    } 
    protected void initParameters(DataParam param) {
        initParamItem(param, "roleId", "");
    }

    protected SecurityUserQuery getService() {
        return (SecurityUserQuery) this.lookupService(this.getServiceId());
    }
}
